import router from '.';
import { loadingRouter } from './routeInit';
export const guard = () => {
  router.beforeEach(async (to, from, next) => {
    const token = localStorage.getItem('token');
    // console.log(router.getRoutes(), to.matched.length);

    // 跳转的是否是登录页
    const isToLoginPage = to.path === '/login';

    if (token) {
      if (isToLoginPage) {
        next(typeof to.query.to === 'string' ? to.query.to : '/');
        return;
      }

      if (to.matched.length === 0) {
        await loadingRouter();
        console.log(router.getRoutes(), to);

        const isExit = router.getRoutes().some((item) => item.path === to.path);
        if (isExit) {
          next({ ...to, replace: true });
        } else {
          next('/404');
        }
      } else {
        next();
      }
      return;
    }

    // 未登录状态 是否跳转登录页
    if (isToLoginPage) {
      next();
    } else {
      if (to.meta && to.meta?.auth) {
        next({ path: '/login', query: { to: to.fullPath } });
      } else {
        next();
      }
    }
  });
};
